package com.zhang.demo.model.db

import android.content.Context
import com.google.gson.reflect.TypeToken
import com.zhang.demo.model.dao.DaoMaster
import com.zhang.demo.model.dao.DaoSession
import com.zhang.demo.model.dao.FileEntityDao
import com.zhang.demo.model.entity.AssetEntity
import com.zhang.demo.model.entity.FileEntity
import com.zhang.demo.utils.GsonUtil
import java.io.IOException
import java.io.InputStreamReader
import javax.inject.Inject

/**
 * Created by zhangke on 2020/8/22 01:11
 * E-Mail Address：2426017569@qq.com
 */
class DBManager  @Inject constructor (var context :Context) {
    private val DB_NAME = "115.db"
    private var mDaoSession: DaoSession? = null
    private var helper: SQLiteOpenHelper? = null

   init {
       helper = SQLiteOpenHelper(context, DB_NAME, null)
       val daoMaster = DaoMaster(helper?.writableDb)
       mDaoSession = daoMaster.newSession()
   }

    fun loadAssetsData():List<FileEntity>{
        try {
            val open = context.assets.open("data.txt")
            val isr = InputStreamReader(open)
            val result = GsonUtil.getGson().fromJson<AssetEntity>(isr, object :
                TypeToken<AssetEntity>() {}.type)

            return result.data
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return emptyList()
    }

    fun getFileEntityDao(): FileEntityDao? {
        return  mDaoSession?.fileEntityDao
    }

    fun isFileEmpty(): Boolean{
        val count = getFileEntityDao()?.queryBuilder()?.count()
        if (count==0L){
            return true
        }
        return false
    }
    fun getFileList(): List<FileEntity>?{
        val list = getFileEntityDao()?.queryBuilder()?.list()
        return list
    }
    fun insertFile(list:List<FileEntity>) {
        getFileEntityDao()?.insertOrReplaceInTx(list)
    }

    fun deleteFile(id: Long) {
        getFileEntityDao()?.deleteByKey(id)
    }
}